package com.ProjetEISD.extraction;

import javax.swing.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Vector;

public class ControlPanel extends JPanel
implements ActionListener,
DocumentListener {

	static final long serialVersionUID = -5516482576609259711L;

	final static boolean MULTICOLORED = false;
	Color bgColor = new Color(255, 255, 255);
	float transparency = 0.1f;
	Image backGround = null;

	private ConversationPane conversPane;

	private static final String buttonString = "Send";
	private JButton sendButton, clearButton;
	private JTextField questionText;
	private Process lua=null;
	private InputStream output=null;

	private int cpt = -1;
	
	private Vector<String> vecConv;

	public ControlPanel() {

		setLayout(new BorderLayout());
		setBorder(BorderFactory.createCompoundBorder(
				BorderFactory.createTitledBorder("Football"),
				BorderFactory.createEmptyBorder(5,5,5,5)));

		JPanel imgPane = new JPanel() {
			//Méthode affichant le contenu désirer (image ou couleur en fond)
			public void paint(Graphics g)
			{
				if ( backGround != null )
				{
//					Graphics2D g2 = (Graphics2D) g;
//					g2.setComposite(java.awt.AlphaComposite.getInstance(
//					java.awt.AlphaComposite.SRC_OVER,Math.min(transparency,1.0f)));
					g.drawImage( backGround, 0, 0, getSize().width, getSize().height, this);
				}
				else
				{
					g.setColor(bgColor);
					g.fillRect(0,0,getSize().width,getSize().height);
				}

			}
		};
		imgPane.setPreferredSize(new Dimension(100, 150));
		drawPanelBackground(imgPane);

		conversPane = new ConversationPane();
		conversPane.setPreferredSize(new Dimension(400, 400));
		JScrollPane jsp = new JScrollPane(conversPane);
		jsp.setPreferredSize(new Dimension(200, 200));
		
		clearButton = new JButton("Clear");
		clearButton.setActionCommand("Clear");
		clearButton.addActionListener(this);
		clearButton.setEnabled(false);

		sendButton = new JButton(buttonString);
		sendButton.setActionCommand(buttonString);
		sendButton.addActionListener(this);
		sendButton.setEnabled(false);

		questionText = new JTextField(10);
		questionText.addActionListener(this);
		questionText.getDocument().addDocumentListener(this);

		//Create a panel that uses BoxLayout.
		JPanel buttonPane = new JPanel();
		buttonPane.setLayout(new BoxLayout(buttonPane,
				BoxLayout.LINE_AXIS));

		buttonPane.add(clearButton);
		
		buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
		buttonPane.add(Box.createHorizontalStrut(5));
		
		buttonPane.add(questionText);

		buttonPane.add(new JSeparator(SwingConstants.VERTICAL));
		buttonPane.add(Box.createHorizontalStrut(5));

		buttonPane.add(sendButton);

		buttonPane.setBorder(BorderFactory.createEmptyBorder(5,5,5,5));

		add(imgPane, BorderLayout.PAGE_START);
//		add(listScrollPane, BorderLayout.CENTER);
		add(jsp, BorderLayout.CENTER);
		add(buttonPane, BorderLayout.PAGE_END);

		vecConv = new Vector<String>();
	}

	//Don't allow this panel to get taller than its preferred size.
	//BoxLayout pays attention to maximum size, though most layout
	//managers don't.
	public Dimension getMaximumSize() {
		return new Dimension(Integer.MAX_VALUE,
				getPreferredSize().height);
	}


	/**
	 * 
	 */
	public void actionPerformed(ActionEvent e) {

		Object src = e.getSource();
		
		if(src==clearButton) {
			System.out.println("clear");
			vecConv.removeAllElements();
			clearButton.setEnabled(false);
			this.repaint();
		}
		else {
		//if(src instanceof JButton) {
		String text = questionText.getText();

		if (text.equals("")) {
			Toolkit.getDefaultToolkit().beep();
			questionText.requestFocusInWindow();
			questionText.selectAll();
			return;
		}
		
//		conversPane.addString(questionText.getText());
		vecConv.add(questionText.getText());
		if(!clearButton.isEnabled())
			clearButton.setEnabled(true);
		this.repaint();

		//Reset the text field.
		questionText.requestFocusInWindow();
		questionText.setText("");


		//}


		/*ExecuteScript executeS = new ExecuteScript();
		executeS.run();*/

		String [] locations={"/net/public/tal/dialogue/bin/idial",
				"/home/dorothy/Documents/tal/dialogue/bin/idial",
		"/home/nicolas/tmp/dialogue/bin/idial"};
		String idial="";
		for (int i=0;i<locations.length;i++)
		{
			File f=new File(locations[i]);
			if (f.exists())
				idial=locations[i];
		}
		try {
			
			if(lua==null)
				lua = Runtime.getRuntime().exec(idial+" footTest_dialogue.lua");
			OutputStream input=lua.getOutputStream();
			output=lua.getInputStream();
			text+="\r";

			System.out.println(text);
			input.write(text.getBytes());
			input.flush();


		}
		catch (Exception ept)
		{
//			le processus n'est pas terminé, OK
			System.out.println("idial running...");
			ept.printStackTrace();
		}

//		Thread t=new Thread() {
		BufferedReader buf=null;

//		public void run()
//		{
		if (buf==null)
		{
			buf=new BufferedReader(new InputStreamReader(output));
		}

		String rep="";

		try {
		System.out.println("idial exit value="+lua.exitValue());
		JOptionPane.showMessageDialog(this,
				"Le programme idial s'est arrêté de manière inattendue",
				"Erreur d'entrée-sortie",JOptionPane.ERROR_MESSAGE);
			lua = Runtime.getRuntime().exec(idial+" footTest_dialogue.lua");
		
		} catch (IllegalThreadStateException ie) {
//			ie.printStackTrace();
		} catch (IOException ioe) {
			// TODO Auto-generated catch block
			ioe.printStackTrace();
		}

		try {
			while((rep = buf.readLine())!=null && !rep.equals("")) {
//				if (rep!=null) {
				System.out.println("ligne ="+rep);
				if (rep.contains("nlg:"))
				{
					cpt++;

					vecConv.add(rep);
					if(!clearButton.isEnabled())
						clearButton.setEnabled(true);
					this.repaint();

				}
				if(cpt==1) {
					cpt=0;
					break;
				}
			}
		}
		catch (IOException ept)
		{
			ept.printStackTrace();
		}
//		}
//		};
		}

	}

	//Required by DocumentListener.
	public void insertUpdate(DocumentEvent e) {
		enableButton();
	}

	//Required by DocumentListener.
	public void removeUpdate(DocumentEvent e) {
		handleEmptyTextField(e);
	}

	//Required by DocumentListener.
	public void changedUpdate(DocumentEvent e) {
		if (!handleEmptyTextField(e)) {
			enableButton();
		}
	}

	private boolean handleEmptyTextField(DocumentEvent e) {
		if (e.getDocument().getLength() <= 0) {
			sendButton.setEnabled(false);
			return true;
		}
		return false;
	}

	private void enableButton() {
		if (!sendButton.isEnabled()) {
			sendButton.setEnabled(true);
		}
	}

	class ExecuteScript extends Thread {

		ExecuteScript() {
			super();
		}

		public void run() {
			try {
				String name = System.getProperty ( "os.name" );

				System.out.println(name);

				/*String ligneCommande = "C:\\WINDOWS\\system32\\notepad.exe";*/
				String cmd = "";

				if(name.equals("Linux")) {
					Process proc = Runtime.getRuntime().exec("");
				} else {
					System.out.println("IN");
					Process proc1 = Runtime.getRuntime().exec("");
//					sleep(1000);
//					Process proc2 = Runtime.getRuntime().exec("");
				}

			} catch (Exception ex) {
				ex.printStackTrace();
			}
		}
	}

	public void drawPanelBackground(JPanel p) {
		if (MULTICOLORED) {
			p.setOpaque(true);
			p.setBackground(bgColor);
		}
		else {
			setImageFile(p, "./fond1.jpg");
			p.repaint();
		}
	}

	//MÈthodes pour mettre une image en fond.
	public void setImageFile(JPanel p, String fichier)
	{
		setImage(loadImages( fichier ));
	}
	public void setImage( Image backGround )
	{
		this.backGround = backGround;
		setOpaque( false );
	}
	private Image loadImages( String imageFile )
	{
		try
		{
			MediaTracker mTrack = new MediaTracker( this ); // load les image avan de les afficher
			Image image = getToolkit().getImage( getURL( imageFile  ) );
			mTrack.addImage( image, 0 );
			mTrack.waitForAll();
			return image;
		}
		catch (Exception e)
		{
			System.out.println( " getimages : " + e );
		}
		return null;
	}
	public URL getURL( String file ) throws MalformedURLException
	{
		URL documentBase = new URL("file:///" + System.getProperty("user.dir") + "/");
		System.out.println("image adr: " + documentBase);
		return new URL( documentBase, file );
	}

	protected class ConversationPane extends JPanel {
		private static final long serialVersionUID = 1L;
		//Méthode affichant le contenu désirer (image ou couleur en fond)
		private int x = 5;
		private int y = 15;
		private int offset = 15;
		private Graphics2D g2;
		
		public void paint(Graphics g) {
			super.paintComponent(g);
			g2 = (Graphics2D) g;
			if ( backGround != null )
			{
//				g2 = (Graphics2D) g;
//				g2.setComposite(java.awt.AlphaComposite.getInstance(
//				java.awt.AlphaComposite.SRC_OVER,Math.min(transparency,1.0f)));
				for(int i=0; i<vecConv.size(); i++) {
					if(vecConv.get(i).startsWith("nlg:"))
						g2.setColor(Color.BLUE);
					else
						g2.setColor(Color.BLACK);
					g2.drawString(vecConv.get(i), x, y+offset*i);
				}
			}
			else
			{
				g2.setColor(bgColor);
				g2.fillRect(0,0,getSize().width,getSize().height);
			}

		}
	}

}
